import { createRouter, createWebHashHistory } from 'vue-router'
import { LOGIN_TOKEN } from '@/global/constants'
import { localCache } from '@/utils/cache'
import { firstMenu } from '@/utils/map-menus'
import { clientSubRoutes } from '@/router/client/index'
import { controlSubRoutes } from '@/router/control/index'
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      redirect: '/client/home'
    },
    {
      name: 'login',
      path: '/login',
      component: () => import('../views/login/login.vue')
    },
    {
      name: 'register',
      path: '/register',
      component: () => import('../views/register/register.vue')
    },
    {
      name: 'client',
      path: '/client',
      redirect: '/client/home',
      component: () => import('../views/client/index.vue'),
      children: clientSubRoutes
    },
    {
      name: 'control',
      path: '/control',
      component: () => import('../views/control/index.vue'),
      children: controlSubRoutes
    },
    {
      path: '/:pathMatch(.*)',
      component: () => import('../views/not-found/not-found.vue')
    },
    {
      name: '客户端华为云产品',
      path: '/client/cloudProduct/hwProduct',
      meta: {
        title: '华为云产品'
      },
      component: () => import('../views/client/cloudProduct/hwProduct.vue')
    },
    {
      name: '客户端华为云账号绑定',
      path: '/client/cloudProduct/bindHw',
      meta: {
        title: '华为云账号绑定'
      },
      component: () => import('../views/client/cloudProduct/bindHw.vue')
    }
  ],
  // 每次切换路由页面滚动到顶部
  scrollBehavior(to, from, savedPosition) {
    return { left: 0, top: 0 }
  }
})

// 用户进行刷新：判断用户是否登录以及是否包含userMenus菜单

// 参数（对应的路由配置对象）：to（跳转到的位置）/from（从哪里跳转过来）
// 返回值：返回值决定导航的路径（不返回或者返回undefined，则默认跳转）
// 举个例子：/ => /login
// to: /login  from: /
router.beforeEach((to) => {
  // 只有登录成功（token），才能进入 main 页面
  const token = localCache.getCache(LOGIN_TOKEN)
  // str.startsWith(xxx) => str是否以xxx开头
  if (to.path.startsWith('/main') && !token) {
    return '/login'
  }

  // 如果是进入main
  if (to.path === '/main') {
    return firstMenu?.url
  }
  // // 如果是进入客户端
  // if (to.path.startsWith('/client')) {
  //   return next()
  // }
})

router.afterEach(() => {
  window.scrollTo(0, 0); // 切换路由之后滚动条始终在最顶部
});

export default router
